﻿@using SubstrateHelper.Models;
@using SubstrateHelper.Data;
@using ProcessBase.Models;
@using System.Collections.Concurrent;
@using System.Collections.Generic;
@using System.Linq;
@using System.Timers;
@inject NavigationManager NavigationManager

<div>
    <Table TItem="ProcessBase.Models.ProcessStatistics" @ref="TheTable"
           IsPagination="true" PageItemsSource="@PageItemsSource"
           IsStriped="true" IsBordered="true"
           ShowToolbar="false" IsMultipleSelect="true" ShowExtendButtons="true"
           ShowDeleteButton="false"
           ShowEditButton="false"
           OnQueryAsync="@OnQueryAsync"
           Height="480">

        <TableColumns>
            <TableColumn @bind-Field="@context.ProcessName" Width="100" Sortable="true" />
            <TableColumn @bind-Field="@context.MainLotNo" Width="100" Sortable="true" />
            <TableColumn @bind-Field="@context.LotNoInput" Width="100" Sortable="true" />
            <TableColumn @bind-Field="@context.LotNoOutput" Width="100" Sortable="true" />
            <TableColumn @bind-Field="@context.QuantityInput" Width="100" Sortable="true" FormatString="0.00" />
            <TableColumn @bind-Field="@context.QuantityInputUnit" Width="100" Sortable="true" />
            <TableColumn @bind-Field="@context.QuantityOutput" Width="100" Sortable="true" FormatString="0.00" />
            <TableColumn @bind-Field="@context.QuantityOutputUnit" Width="100" Sortable="true" />
            <TableColumn @bind-Field="@context.DateIn" Width="100" Sortable="true" FormatString="yyyy/MM/dd" />
            <TableColumn @bind-Field="@context.DateOut" Width="100" Sortable="true" FormatString="yyyy/MM/dd" />
            <TableColumn @bind-Field="@context.ProcessState" Width="100" Sortable="true" />
            <TableColumn @bind-Field="@context.QualityState" Width="100" Sortable="true" />


        </TableColumns>
        <RowButtonTemplate>
            <span>
                <NavLink href="@($"/PageShowDetail/{context.Guid}")" target="_blank">明细</NavLink>
            </span>
            
            <span class="ml-2">
                <NavLink href="@($"/DownloadProcesses/{context.Guid}")" target="_blank">导出流程</NavLink>
            </span>
            
        </RowButtonTemplate>

    </Table>
</div>

<hr class="bg-primary" style="height:5px;" />
<div class="mt-2">
    <span>
        <span class="text-secondary"><strong class="text-primary">选定来料 </strong>合计:</span>
        <input type="number" @bind="InputSum" class="number_input" disabled />
    </span>
    <span class="ml-5">
        <span class="text-secondary">平均:</span>
        <input type="number" @bind="InputAvg" class="number_input" disabled />
    </span>
    <span class="ml-5">
        <span class="text-secondary">最大:</span>
        <input type="number" @bind="InputMax" class="number_input" disabled />
    </span>
    <span class="ml-5">
        <span class="text-secondary">最小:</span>
        <input type="number" @bind="InputMin" class="number_input" disabled />
    </span>

    <span class="ml-5">
        <span class="text-secondary">选定条数 :</span>
        <input type="number" @bind="SelectedCount" class="number_input" disabled />
    </span>
</div>
<div class="mt-2">
    <span>
        <span class="text-secondary"><strong class="text-primary">选定产出 </strong>合计:</span>
        <input type="number" @bind="OutputSum" class="number_input" disabled />
    </span>
    <span class="ml-5">
        <span class="text-secondary">平均:</span>
        <input type="number" @bind="OutputAvg" class="number_input" disabled />
    </span>
    <span class="ml-5">
        <span class="text-secondary">最大:</span>
        <input type="number" @bind="OutputMax" class="number_input" disabled />
    </span>
    <span class="ml-5">
        <span class="text-secondary">最小:</span>
        <input type="number" @bind="OutputMin" class="number_input" disabled />
    </span>

    <span class="ml-5">
        <span class="text-secondary">产出/来料:</span>
        <input type="number" @bind="OutPerIn" class="number_input" disabled />
    </span>

</div>

@code {

    double? InputSum { get; set; }
    double? InputAvg { get; set; }
    double? InputMax { get; set; }
    double? InputMin { get; set; }

    double? OutputSum { get; set; }
    double? OutputAvg { get; set; }
    double? OutputMax { get; set; }
    double? OutputMin { get; set; }

    double? OutPerIn { get; set; }

    int SelectedCount { get; set; }

    private Table<ProcessBase.Models.ProcessStatistics> TheTable;
    protected IEnumerable<int> PageItemsSource => new int[] { 50, 100, 200 };

    [Parameter]
    public List<ProcessBase.Models.ProcessStatistics> Items
    {
        get
        {
            return _Items;
        }
        set
        {
            _Items = value;
            if (TheTable != null)
            {
                TheTable.PageItemsSource = null;
                TheTable.PageItemsSource = PageItemsSource;
                TheTable.QueryAsync();

            }

        }
    }
    List<ProcessBase.Models.ProcessStatistics> _Items;

    private static readonly ConcurrentDictionary<Type, Func<IEnumerable<ProcessBase.Models.ProcessStatistics>, string, SortOrder, IEnumerable<ProcessBase.Models.ProcessStatistics>>> SortLambdaCache = new ConcurrentDictionary<Type, Func<IEnumerable<ProcessBase.Models.ProcessStatistics>, string, SortOrder, IEnumerable<ProcessBase.Models.ProcessStatistics>>>();
    protected ProcessBase.Models.ProcessStatistics SearchModel { get; set; } = new ProcessBase.Models.ProcessStatistics();

    protected Task<QueryData<ProcessBase.Models.ProcessStatistics>> OnQueryAsync(QueryPageOptions options)
    {
        if (Items == null)
        {
            return Task.FromResult(new QueryData<ProcessBase.Models.ProcessStatistics>());
        }

        IEnumerable<ProcessBase.Models.ProcessStatistics> items = Items;

        // 过滤
        var isFiltered = false;
        if (options.Filters.Any())
        {
            items = items.Where(options.Filters.GetFilterFunc<ProcessBase.Models.ProcessStatistics>());
            isFiltered = true;
        }

        // 排序
        var isSorted = false;
        if (!string.IsNullOrEmpty(options.SortName))
        {
            // 外部未进行排序，内部自动进行排序处理
            var invoker = SortLambdaCache.GetOrAdd(typeof(ProcessBase.Models.ProcessStatistics), key => LambdaExtensions.GetSortLambda<ProcessBase.Models.ProcessStatistics>().Compile());
            items = invoker(items, options.SortName, options.SortOrder);
            isSorted = true;
        }

        // 设置记录总数
        var total = items.Count();

        // 内存分页
        items = items.Skip((options.PageIndex - 1) * options.PageItems).Take(options.PageItems).ToList();

        return Task.FromResult(new QueryData<ProcessBase.Models.ProcessStatistics>()
        {
            Items = items,
            TotalCount = total,
            IsSorted = isSorted,
            IsFiltered = isFiltered
        });
    }



    System.Timers.Timer Timer;
    protected override async Task OnInitializedAsync()
    {



        //定时器->自动更新用户选择片数
        Timer = new System.Timers.Timer(500);
        Timer.Elapsed += (o, e) =>
        {
            InvokeAsync(() =>
            {

                try
                {
                    var selected = TheTable.SelectedRows;
                    if (selected != null)
                    {
                        SelectedCount = selected.Count();
                        var queryInput = selected.Where(x => x.QuantityInput != null).Select(x => x.QuantityInput.Value);
                        InputSum = queryInput.Sum();
                        InputAvg = queryInput.Average();
                        InputMax = queryInput.Max();
                        InputMin = queryInput.Min();

                        var queryOutput = selected.Where(x => x.QuantityOutput != null).Select(x => x.QuantityOutput.Value);
                        OutputSum = queryOutput.Sum();
                        OutputAvg = queryOutput.Average();
                        OutputMax = queryOutput.Max();
                        OutputMin = queryOutput.Min();

                        OutPerIn = OutputSum.Value / InputSum.Value;
                    }
                    else
                    {
                        SelectedCount = 0;
                        InputSum = null;
                        InputAvg = null;
                        InputMax = null;
                        InputMin = null;
                        OutputSum = null;
                        OutputAvg = null;
                        OutputMax = null;
                        OutputMin = null;

                        OutPerIn = null;
                    }

                }
                catch
                {
                    SelectedCount = 0;
                    InputSum = null;
                    InputAvg = null;
                    InputMax = null;
                    InputMin = null;
                    OutputSum = null;
                    OutputAvg = null;
                    OutputMax = null;
                    OutputMin = null;
                    OutPerIn = null;
                }

                StateHasChanged();
            });


        };
        Timer.Enabled = true;


    }

    private async Task OnRowButtonClick(ProcessBase.Models.ProcessStatistics item)
    {

        NavigationManager.NavigateTo("PageShowDetail", true);
    }


}
